from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render,redirect
from django.views import View
from django import http
import re
from django.contrib.auth import login,authenticate,logout
from django_redis import get_redis_connection
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
import json
# from django.core.mail import send_mail
from django.core.mail import send_mail
from django.db import DatabaseError
import logging
# from .utils import generate_verify_email_url, get_user_check_token
logger = logging.getLogger('django')




from .models import User,Address
from meiduo_mail.utils.response_code import RETCODE
from meiduo_mail.utils.views import LoginRequiredView
from celery_tasks.email.tasks import send_verify_email
from .utils import generate_verify_email_url,get_user_check_token
from goods.models import SKU
from carts.utils import merage_cart_cookie_to_redis
from orders.models import OrderInfo,OrderGoods


#E


class RegisterView(View):
    """注册"""

    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):

        # 1.接收请求体表单数据  POST
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        password2 = query_dict.get('password2')
        mobile = query_dict.get('mobile')
        sms_code = query_dict.get('sms_code')
        allow = query_dict.get('allow')  # 如果表单中的复选框没有指定value时勾选 传入的是'on' 反之 None

        # 2.校验数据  '' {} [] False None
        # all( [] )  返回True , False
        if all([username, password, password2, mobile, sms_code, allow]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        if password != password2:
            return http.HttpResponseForbidden('输入两次密码不一致')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')

        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        # 获取redis数据库中当前用户短信验证码
        sms_code_server_bytes = redis_conn.get('sms_%s' % mobile)

        # 删除已经取出的短信验证码,让它只能被用一次
        redis_conn.delete('sms_%s' % mobile)

        # 判断redis中短信验证码过期
        if sms_code_server_bytes is None:
            return http.JsonResponse({'code': RETCODE.SMSCODERR, 'errmsg': '短信验证码已过期'})
        # 将bytes类型转换为字符串类型
        sms_code_server = sms_code_server_bytes.decode()
        # 用户填写的和redis中的短信验证码是否一致
        if sms_code != sms_code_server:
            return http.JsonResponse({'code': RETCODE.SMSCODERR, 'errmsg': '短信验证码填写错误'})

        # 创建user并且存储到表中
        # user = User.objects.create(
        #     username = username,
        #     password =password
        #     mobile = mobile
        # )
        # user.set_password(password)
        # user.save()
        # 创建并保存用户
        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # 用户注册成功即代表登录成功(状态保持)
        # request.session['id'] = user.id
        #
        # user_id = request.session['id']
        login(request, user)
        response = redirect('/')
        response.set_cookie('username', user.username, max_age=settings.SESSION_COOKIE_AGE)
        # 响应()
        # return http.HttpResponse('注册成功,应该去到首页')
        return response





class UsernameCountView(View):
    """判断用户名是否重复"""
    def get(self, request, username):
        # print("yonghuchongming")
        # 查询username的数量
        count = User.objects.filter(username=username).count()

        data = {
            'count': count,
            'code': RETCODE.OK,
            'errmsg': 'OK'
        }
        # 响应
        return http.JsonResponse(data)
    # def get(self, request, username):
    #     """
    #     :param request: 请求对象
    #     :param username: 用户名
    #     :return: JSON
    #     """
    #     count = User.objects.filter(username=username).count()
    #     return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):

    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            'count':count,
            'code':RETCODE.OK,
            'errmsg':'ok'
        }
        return http.JsonResponse(data)


class LoginView(View):
    """登录"""

    def get(self, request):
        return render(request, 'login.html')
    def post(self, request):
        # 接收请求表单数据
        query_dict = request.POST
        # print(query_dict.dict().keys())
        username = query_dict.get('username')
        password = query_dict.get('password')
        remembered = query_dict.get('remembered')

        # 校验
        if all([username, password]) is False:
            return http.HttpResponseForbidden('缺少必传参数')


        # 用户登录认证验证
        user = authenticate(request, username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})
        # user = User.objects.get(username=username)
        # user.check_password(password)

        # user = User.objects.get(username=username)
        # user.check_password(password)

        # 状态操持
        login(request, user)
        # 如果用户没有勾选记住登录,设置session过期时间为会话结束
        # if remembered is None:
        #     request.session.set_expiry(0)
        # else:
        #     request.session.set_expiry(3600 * 24 * 7)

        # request.session.set_expiry(0 if remembered is None else (3600 * 24 * 7))
        request.session.set_expiry(None if remembered else 0)

        next = request.GET.get('next')
        response = redirect(next or '/')


        # 创建响应对象
        # response = redirect('/')
        # 用户登录成功后向cookie中存储username
        # response.set_cookie('username', user.username, max_age=None if remembered is None else settings.SESSION_COOKIE_AGE)
        response.set_cookie('username', user.username, max_age=remembered and settings.SESSION_COOKIE_AGE)
        # 重定向到首页
        merage_cart_cookie_to_redis(request, response)
        # 重定向到首页
        # return http.HttpResponse('登录成功,跳转到首页界面')
        return response



class LogoutView(View):
    """退出登录"""

    def get(self, request):
        # 1.清除状态操持
        logout(request)

        # 创建响应对象
        response = redirect('users:login')
        # 2.清除cookie中的username
        response.delete_cookie('username')

        # 3.重定向到login
        return response



# class InfoView(View):
#     """用户中心"""
#     def get(self,request):
#         user = request.user
#         if user.is_authenticated:
#             return render(request,'user_center_info.html')
#         else:
#             # return redirect('users:login')
#             return redirect('/login/?next=/info/')
#             # return redirect('/login/?next=/info/')



# class InfoView(LoginRequiredMixin, View):
#     """用户中心"""
#     def get(self, request):
#         return render(request, 'user_center_info.html')



# @method_decorator(login_required, name='get')
# class InfoView(View):
#     """用户中心"""
#     def get(self, request):
#         return render(request, 'user_center_info.html')
class InfoView(LoginRequiredMixin, View):
    """用户中心"""
    def get(self, request):
        return render(request, 'user_center_info.html')


class EmailView(LoginRequiredView):

    def put(self, request):
        # 1.接收请求体非表单数据 body
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 2.校验
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('邮箱格式有误')

        # 3.修改user模型的email字段

        user = request.user
        # 如果用户还没有设置邮箱再去设置,如果设置过了就不要再设置了
        if user.email != email:
            user.email = email
            user.save()

        # 给当前设置的邮箱发一封激活url
        # send_mail(subject='邮件的标题/主题', message='普通字符串邮件正文', from_email='发件人', recipient_list=['收件人邮箱'],
              # html_message='超文本邮件正文')
        # html_message = '<p>这是一个激活邮件 <a href="http://www.baidu.com">点我一下<a></p>'
        # send_mail(subject='激活邮箱', message='普通字符串邮件正文', from_email='美多商城<itcast99@163.com>', recipient_list=[email],
        #       html_message=html_message)
        verify_url = generate_verify_email_url(user)
        send_verify_email.delay(email, verify_url)
        # 响应
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})




class EmailVerifyView(View):
    """激活邮箱"""
    def get(self,request):
        token = request.GET.get('token')
        user = get_user_check_token(token)
        if user is None:
            return http.HttpResponseForbidden('激活失败')
        user.email_active = True
        user.save()
        return render(request,'user_center_info.html')


class AddressesView(LoginRequiredView):
    """用户收获地址"""
    # def get(self,request):
    #     user = request.user
    #     address_qs = Address.objects.filter(user=user,is_deleted=False)
    #     address_list = []
    #     for address in address_qs:
    #         address_list.append({
    #             'id': address.id,
    #             'title': address.title,
    #             'receiver': address.receiver,
    #             'province_id': address.province_id,
    #             'province': address.province.name,
    #             'city_id': address.city_id,
    #             'city': address.city.name,
    #             'district_id': address.district_id,
    #             'district': address.district.name,
    #             'place': address.place,
    #             'mobile': address.mobile,
    #             'tel': address.tel,
    #             'email': address.email
    #         })
    #         context = {
    #             'addresses': address_list,
    #             'default_address_id': user.default_address_id
    #         }
    #
    #         return render(request, 'user_center_site.html', context)
    def get(self, request):
        user = request.user
        address_qs = Address.objects.filter(user=user,is_deleted=False)
        address_list = []
        for address in address_qs:
            address_list.append({
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province_id': address.province_id,
                'province': address.province.name,
                'city_id': address.city_id,
                'city': address.city.name,
                'district_id': address.district_id,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email
            })


        context = {
            'addresses': address_list,
            # 'addresses': address_list,
            'default_address_id': user.default_address_id
            # 'default_address_id': user.default_address_id
        }
        return render(request, 'user_center_site.html', context)
        # return render(request, 'user_center_site.html', context)

class AddressCreateView(LoginRequiredView):
    """新增收获地址"""
    # def post(self, request):
    #     json_dict = json.loads(request.body.decode())
    #     title = json_dict.get('title')
    #     receiver = json_dict.get('receiver')
    #     province_id = json_dict.get('province_id')
    #     city_id = json_dict.get('city_id ')
    #     district_id = json_dict.get('district_id')
    #     place = json_dict.get('place')
    #     mobile = json_dict.get('mobile')
    #     tel = json_dict.get('tel')
    #     email = json_dict.get('email')
    def post(self, request):

        # 1.接收请求体非表单数据 body
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        if all([title,receiver,province_id,city_id,district_id,place,mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('手机号格式有误')

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')
        user = request.user

        try:
            address = Address.objects.create(
                user=user,
                title=title,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except DatabaseError as e:
            logger.error(e)
            return http.HttpResponseForbidden('新增收获地址错误')
        # if user.default_address is None:
        #     user.default_address = address
        #     user.save()
        if user.default_address is None:
            # 给用户设置一个默认地址
            user.default_address = address
            user.save()

        address_dict = {
            'id': address.id,
            'receiver':  address.receiver,
            'province_id':  address.province_id,
            'city_id':  address.city_id,
            'district_id':  address.district_id,
            'place':  address.place,
            'mobile':  address.mobile,
            'tel':  address.tel,
            'email':  address.email
        }

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address': address_dict})



class UpdateDestroyAddressView(LoginRequiredView):
    """修改和删除用户收货地址"""
    def put(self,request,address_id):
        user = request.user
        try:
            address = Address.objects.get(id=address_id, user=user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id有错误')

        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        if all([title,receiver,province_id,city_id,district_id,place,mobile]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('手机号格式有误')

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')


        # 修改用户地址数据，重新赋值
        address.title = title
        address.receiver = receiver
        address.province_id = province_id
        address.city_id = city_id
        address.district_id = district_id
        address.place = place
        address.mobile = mobile
        address.tel = tel
        address.email = email
        address.save()

        address_dict = {
            'id': address.id,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'city_id': address.city_id,
            'district_id': address.district_id,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email
        }

        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'修改成功','address':address_dict})

    def delete(self,request,address_id):

        user = request.user
        # 校验address_id
        try:
            address = Address.objects.get(id=address_id, user=user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('address_id有错误')
        # 将address的is_delete字段设置为True 做逻辑删除
        address.is_deleted = True
        address.save()
        # 响应
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'删除成功'})



class UpdateTitleAddressView(LoginRequiredView):
    """设置地址标题"""

    def put(self, request, address_id):
        """设置地址标题"""
        # 接收参数：地址标题
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置地址标题成功'})


class UserDefaultAddressView(LoginRequiredView):

    def put(self,request,address_id):
        user = request.user

        try:
            address = Address.objects.get(id=address_id, user=user, is_deleted=False)
        except Address.DoesNotExist:
            return http.HttpResponseForbidden('地址信息错误')
        user.default_address = address
        user.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg':'OK'})


class ChangeUserPasswordView(LoginRequiredView):

    def get(self,request):
        return render(request,'user_center_pass.html')

    def post(self,request):
        # 接收请求体表单数据
        query_dict = request.POST
        old_pwd = query_dict.get('old_pwd')
        new_pwd = query_dict.get('new_pwd')
        new_cpwd = query_dict.get('new_cpwd')
        # 校验
        if all([old_pwd,new_pwd,new_cpwd]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        user = request.user
        if user.check_password(old_pwd) is False:
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '原始密码有误'})
        if not re.match(r'^[0-9a-zA-Z]{8,20}$',new_pwd):
            return http.HttpResponseForbidden('密码不符合规范密码最少8位，最长20位')
        if new_pwd != new_cpwd:
            return http.HttpResponseForbidden('两次密码不一致')
        # 修改用户的password值: 对密码加密后再存储
        user.set_password(new_pwd)
        user.save()
        # 清除状态保持
        logout(request)
        response = redirect('/login/')
        # 将cookie中的username清除
        response.delete_cookie('username')
        return response




class UserBrowseHistory(View):
    def post(self,request):

        # if not user.is_authenticated:
        #     return  http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '未登录用户不能添加浏览记录'})
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        try:
            SKU.objects.get(id=sku_id, is_launched=True)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('skuid不存在')


        redis_conn = get_redis_connection('history')
        user = request.user
        key = 'history_%s' % user.id
        pl = redis_conn.pipeline()
        pl.lrem(key, 0, sku_id)
        pl.lpush(key, sku_id)
        pl.ltrim(key, 0, 4)
        pl.execute()

        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK'})

    def get(self,request):
        user = request.user
        if not user.is_authenticated:
            return http.JsonResponse({'code':RETCODE.SESSIONERR,'errmsg':'未登录用户没有浏览记录'})
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % user.id,0,-1)
        sku_list = []
        for sku_id in sku_ids:
            # 查询sku模型
            sku_model = SKU.objects.get(id=sku_id)
            # sku模型转换成字典
            sku_list.append(
                {
                    'id': sku_model.id,
                    'default_image_url': sku_model.default_image.url,
                    'name': sku_model.name,
                    'price': sku_model.price
                }
            )
        return  http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK','skus':sku_list})

# class UserAllOrder(LoginRequiredView):
#     def get(self,request):
#         user =request.user
#         order_qs = OrderInfo.objects.filter(user=user)
#
#         context_list = []
#         order_list = []
#         order = []
#         for orders in order_qs:
#             # order_list.append({
#             #     'order_id' : orders.order_id,
#             # })
#             order.append(orders)
#
#             order_goods_qs = OrderGoods.objects.filter(order_id=orders.order_id)
#             # for sku in order_goods_qs:
#             sku_list = []
#             for order_good in order_goods_qs:
#                 sku = SKU.objects.get(id=order_good.sku_id)
#             # skus = SKU.objects.filter(id__in=cart.keys())
#             # skus = SKU.objects.get(id=order_goods_qs.sku_id)
#                 sku_list.append({
#                     'name': sku.name,
#                     'default_image' :sku.default_image
#                 })
#                 # for sku in skus:
#                 #     sku_list.append({
#                 #         'name' :sku.name,
#                 #         'default_image' :sku.default_image
#                 #     })
#
#             # for skus.sku_id in order_goods_qs:
#             #     order_dict[]
#             # kk = '1' if OrderInfo.PAY_METHODS_ENUM==OrderInfo.PAY_METHODS_ENUM['CASH'] else '2'
#
#             if OrderInfo.pay_method==1:
#                 kk = '支付宝'
#             else:
#                 kk = '货到付款'
#
#         # st = 0
#         # OrderInfo.ORDER_STATUS_ENUM['UNPAID'] if orders.pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY']
#         # else OrderInfo.ORDER_STATUS_ENUM['UNSEND']
#             if int(orders.status) == 1:
#                 st = '待支付'
#             elif int(orders.status) == 2:
#                 st = '待发货'
#             elif int(orders.status) == 3:
#                 st = '待收货'
#             elif int(orders.status) == 4:
#                 st = '待评价'
#             elif int(orders.status) == 5:
#                 st = '已完成'
#             else:
#                 st = '已取消'
#
#             paginator = Paginator(skus, constants.GOODS_LIST_LIMIT)
#             # 获取每页商品数据
#             try:
#                 page_skus = paginator.page(page_num)
#             except EmptyPage:
#                 # 如果page_num不正确，默认给用户404
#                 return http.HttpResponseNotFound('empty page')
#             # 获取列表页总页数
#             total_page = paginator.num_pages
#
#             # context = {
#             #     'create_time' :orders.create_time,
#             #     'order_id' : orders.order_id,
#             #     # 'default_image.url': sku.default_image,
#             #     # 'sku.name' : sku.name,
#             #     'sku_list':sku_list,
#             #     'total_amount' :orders.total_amount,
#             #     'freight':orders.freight,
#             #     'pay_method_name': kk,
#             #     'status': orders.status,
#             #     'status_name' : st,
#             #     }
#             # # context_list.append(context)
#             # return render(request,'user_center_order.html',context)
#             # order = {
#             #     'order':orders,
#             #     'order_id' : orders.order_id,
#             #
#             #
#             # }
#
#             # context.append(order)
#         #     context = {
#         #         'sku_list' :sku_list,
#         #         'order' : orders,
#         #         'pay_method_name': kk,
#         #         'status_name': st
#         #     }
#         #     order_list.append(context)
#         # # return render(request, 'user_center_order.html', order_list)
#
#
#
#
#             # skus = SKU.objects.filter(id=OrderGoods.sku_id)
#
#             # order_goods_list = []
#             # for order_goods in order_goods_qs:
#             #     order_goods_list.append({
#             #         'order_id' : orders.order_id,
#             #         'name' : order_goods.name,
#             #         'count' : order_goods.count,
#             #         'price' : order_goods.price,
#             #
#             #
#             #     })

class UserAllOrder(LoginRequiredView):
    def get(self,request,page_num):
        user =request.user
        order_qs = OrderInfo.objects.filter(user=user)


        for order in order_qs:

            # order.append(orders)

            order_goods_qs = OrderGoods.objects.filter(order_id=order.order_id).order_by('create_time')


            if OrderInfo.pay_method == 2:
                kk = '支付宝'
            else:
                kk = '货到付款'
            if int(order.status) == 1:
                st = '待支付'
            elif int(order.status) == 2:
                st = '待发货'
            elif int(order.status) == 3:
                st = '待收货'
            elif int(order.status) == 4:
                st = '待评价'
            elif int(order.status) == 5:
                st = '已完成'
            else:
                st = '已取消'

            if OrderInfo.pay_method == 1:
                kk = '支付宝'
            else:
                kk = '货到付款'
            order.status_name = st
            order.pay_method_name = kk
            sku_list = []
            for order_goods in order_goods_qs:
                sku = SKU.objects.get(id=order_goods.sku_id)

                sku.count = order_goods.count
                sku.amount = sku.count * sku.price
                sku_list.append(sku)
            order.sku_list = sku_list
        paginator = Paginator(order_qs,2)

        # 获取每页商品数据
        try:
            page_orders = paginator.page(page_num)
        except EmptyPage:
            # 如果page_num不正确，默认给用户404
            return http.HttpResponseNotFound('empty page')
            # 获取列表页总页数
        total_page = paginator.num_pages
        context ={
            'total_page' :total_page,
            'page_num' :page_num,
            'page_orders' :page_orders
        }
        return render(request,'user_center_order.html',context)
        # return render(request,'user_center_order.html')



class CommentView(LoginRequiredView):
    def get(self,request):
        user = request.user
        # order_qs = OrderInfo.objects.filter(user=user,status=4)

        # for order in order_qs:
        order_id = request.GET.get('order_id')
        order_goods_qs = OrderGoods.objects.filter(order_id=order_id)
        order_goods_list = []
        for order_goods in order_goods_qs:
            # sku = SKU.objects.get(id=order_goods.id)
            # sku.display = 5

            sku = SKU.objects.get(id=order_goods.sku_id)
            sku.is_anonymous = False
            # for sku in skus:
            #     sku.display_score = 5
            # #     order_goods_list.append(sku)
            # for sku in sku_qs:
            #     sku.display_score = 5
            #     order_goods_list.append(sku)
            order_goods_list.append({

                'sku_id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': str(sku.price),
                'is_anonymous': str(sku.is_anonymous),
            })

        # id
        # ': sku_id,
        # 'naem': sku.name,
        # 'default_image_url': sku.default_image.url,
        # 'price': str(sku.price),
        # 'count': count,
        # 'selected': selected,
        # 'amout': sku.price * count

        # context = {
        #     'uncomment_goods_list' : order_goods_list
        #     # 'skus' : skus
        # }
        context = {
            'uncomment_goods_list': order_goods_list,

        }


        return render(request,'goods_judge.html',context)

    def post(self,requsest):
        pass







